// files.cpp : Defines the entry point for the console application.
//

#include <Windows.h>
#include <iostream>

int main(int argc, char* argv[])
{

	HANDLE hFile, hAppend, hNonExistent;
	DWORD dwBytesRead, dwBytesWritten, dwPos;
	char buff[4096];
	TCHAR szMsg[1000];

	using namespace std;
	cout << "winapi files tests:\n";
	cout << "1) open if existing for read: ";
	hFile = CreateFile (TEXT("existing.txt"),   
                      GENERIC_READ,           
                      0,                      
                      NULL,                   
                      OPEN_EXISTING,          
                      FILE_ATTRIBUTE_NORMAL,  
                      NULL);                  
	cout << (hFile != INVALID_HANDLE_VALUE ? "ok" : "failed") << endl;

	cout << "2) must return INVALID_HANDLE_VALUE for nonexistent file: ";
	hNonExistent = CreateFile (TEXT("nonexistent.txt"),   
                      GENERIC_READ,           
                      0,                      
                      NULL,                   
                      OPEN_EXISTING,          
                      FILE_ATTRIBUTE_NORMAL,  
                      NULL);                  
	cout << (hNonExistent == INVALID_HANDLE_VALUE ? "ok" : "failed") << endl;

	cout << "3) open or create for write: ";
	hAppend = CreateFile (TEXT("created.txt"),      
                        GENERIC_WRITE,          
                        0,                      
                        NULL,                   
                        OPEN_ALWAYS,            
                        FILE_ATTRIBUTE_NORMAL,  
                        NULL);                  

	bool r = (hAppend != INVALID_HANDLE_VALUE);
	cout << (r ? "ok" : "failed") << endl;
	if ( !r )
	{
		CloseHandle (hFile);            
		return 0;
	}

	cout << "4) read/write test:\n";
	dwPos = SetFilePointer (hAppend, 0, NULL, FILE_END);
	do
	{
		if (ReadFile (hFile, buff, 4096, &dwBytesRead, NULL))
		{
			cout << "\tread: " << dwBytesRead << " bytes\n";
			if (WriteFile (hAppend, buff, dwBytesRead, &dwBytesWritten, NULL))
			{
				cout << "\twritten: " << dwBytesWritten << " bytes\n";
			}
			else
			{
				cerr << "(!) failed to write\n";
			}
		}
	}
	while (dwBytesRead == 4096);

  // Close both files
	CloseHandle (hFile);
	CloseHandle (hAppend);

	return 0;
}
